//
//  MHCircleHomeModel.m
//  MiaoCircle
//
//  Created by 许正荣 on 2018/4/13.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHCircleHomeViewModel.h"
#import "MHCircleHomeModel.h"
#import "MHHomeCirleItemViewModel.h"
#import "MHSetCircleInfoViewModel.h"
#import "MHCircleInfo.h"
#import "MHMomentViewModel.h"
#import "MHMomentViewModel.h"
#import "MLCircleInfoMainPageViewModel.h"
#import "MHTestViewModel.h"
#import "MHIMMessageTransferHelper.h"
#import "MHCircleUpdateModel.h"

@interface MHCircleHomeViewModel ()
@property (nonatomic, readwrite, strong) RACCommand *rightButtonCommand;
@end
@implementation MHCircleHomeViewModel

- (void)initialize
{
    [super initialize];
    self.title =  LSSTRING("圈子");
    
    self.rightImageStr = @"";
    self.perPage = 12;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = YES;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = YES;
    /// 没有数据时，隐藏底部刷新控件
    self.shouldEndRefreshingWithNoMoreData = NO ;
    
    
    @weakify(self);
    //圈子列表
    RAC(self, circles) = self.requestRemoteDataCommand.executionSignals.switchToLatest;
    /// 数据源
    RAC(self,dataSource) = [RACObserve(self, circles) map:^(NSArray * circles) {
        @strongify(self)
        return [self dataSourceWithCircles:circles];
    }];
    
    self.rightButtonCommand  = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        MHMomentViewModel *viewModel = [[MHMomentViewModel alloc] initWithServices:self.services params:@{MHViewModelUtilKey:@1,MHViewModelTitleKey:@"动态"}];
        //不带用户ID;
        //          viewModel.userId = [MHHTTPService sharedInstance].currentUser.userId;
        viewModel.isRecent = YES;
        [self.services pushViewModel:viewModel animated:YES];
        
        return [RACSignal empty];
    }];
    
    self.leftButtonCommand  = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
        @strongify(self);
        MHSetCircleInfoViewModel *viewModel = [[MHSetCircleInfoViewModel alloc] initWithServices:self.services params:@{MHViewModelIsCreate :@(true)}];
        [self.services pushViewModel:viewModel animated:YES];
        return [RACSignal empty];
    }];
    
    self.didSelectCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(NSIndexPath * indexPath) {
        @strongify(self);
        /// 这里只是测试
        [[IMAPlatform sharedInstance].conversationMgr releaseChattingConversation];
        MHCircleHomeModel *circle = self.circles[indexPath.row];
        //        MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(circle.autoId)}];
        //        [self.services pushViewModel:viewModel animated:YES];
        
        
        IMAUser *user =  [[IMAPlatform sharedInstance].contactMgr getUserByGroupId:circle.circleCode];
        __weak __typeof(self)weakSelf = self;
        if(!user)
        {
            [[TIMGroupManager sharedInstance] joinGroup:circle.circleCode msg:@"" succ:^(){

                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                    TIMGroupInfo *info = [[IMAPlatform sharedInstance].contactMgr syncGetGroupInfo:circle.circleCode];
                    IMAGroup *user = [[IMAGroup alloc] initWith:circle.circleCode];
                    
                    MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:weakSelf.services params:@{MHViewModelUtilKey:user,MHViewModelIDKey:@(circle.autoId)}];
                    viewModel.title = circle.title;
                    //                    viewModel.info = info;
                    [weakSelf.services pushViewModel:viewModel animated:YES];
                });
            }fail:^(int code, NSString * err) {
                
                MLCircleInfoMainPageViewModel *viewModel = [[MLCircleInfoMainPageViewModel alloc] initWithServices:self.services params:@{MHViewModelIDKey:@(circle.autoId)}];
                [self.services pushViewModel:viewModel animated:YES];
            
            }];
        }else
        {
            MHChatViewModel *viewModel = [[MHChatViewModel alloc] initWithServices:weakSelf.services params:@{MHViewModelUtilKey:user,MHViewModelIDKey:@(circle.autoId)}];
            viewModel.title = circle.title;
//            viewModel.circleId = circle.;
            [weakSelf.services pushViewModel:viewModel animated:YES];
           
            
        }
        return [RACSignal empty];
    }];
    
}



/// 请求数据
- (RACSignal *)requestRemoteDataSignalWithPage:(NSUInteger)page{
    
    NSArray * (^mapCircles)(NSArray *) = ^(NSArray *products) {
        if (page == 1) {
            /// 下拉刷新
        } else {
            /// 上拉加载
            products = @[(self.circles ?: @[]).rac_sequence, products.rac_sequence].rac_sequence.flatten.array;
        }
        
        return products;
    };
    return  [[[self.services.client fetchHomeCircleDataWithPageNum:page pageSize:self.perPage]mh_parsedResults] map:mapCircles];
}

#pragma mark - 辅助方法
- (NSArray *)dataSourceWithCircles:(NSArray *)circles {
    if (MHObjectIsNil(circles) || circles.count == 0) return @[];
    NSArray *viewModels = [circles.rac_sequence map:^(MHCircleHomeModel *homeCircle) {
        
        MHHomeCirleItemViewModel *viewModel = [[MHHomeCirleItemViewModel alloc] initWithCircle:homeCircle];
//        viewModel.cacheImGroupLastUpdateDic = [AXAppDelegate sharedDelegate].imGroupImMessageUpdate;
        return viewModel;
    }].array;
    return viewModels ?: @[] ;
}




@end
